const express = require('express')
const router = express.Router()
const models = require('../../models')
const Op = models.Sequelize.Op
const bcrypt = require('bcryptjs')
const toBoolean = require('../../utils/to-boolean')
const {success, error} = require('../../utils/message')
const checkPermission = require('../../middlewares/check-permission');

// 前端用户、管理员列表
router.get('/', checkPermission(), async function (req, res, next) {
    const username = req.query.username
    const admin = req.query.admin
    const currentPage = parseInt(req.query.currentPage) || 1
    const pageSize = parseInt(req.query.pageSize) || 10
    const where = {}

    // 模糊查询
    if (username) {
        where.username = {
            [Op.like]: '%' + username + '%'
        }
    }

    // 筛选管理员
    if (admin) {
        where.admin = {
            [Op.eq]: toBoolean(admin)
        }
    }

    const result = await models.User.findAndCountAll({
        order: [['admin', 'DESC']],  // 管理员账户排在前面
        where: where,
        offset: (currentPage - 1) * pageSize,
        limit: pageSize,
        include: [{
            model: models.Role,
            as: 'role'
        }]
    })

    const data = {
        users: result.rows,
        pagination: {
            currentPage: currentPage,
            pageSize: pageSize,
            total: result.count
        }
    }

    return success(res, '查询成功', data)
})

// 新增管理员
router.post('/', checkPermission(), async function (req, res, next) {
    const username = req.body.username
    const password = req.body.password
    const roleId = req.body.roleId
    const avatar = req.body.avatar

    if (!username) {
        return error(res, '账号必须填写！')
    }

    if (!password) {
        return error(res, '密码必须填写！')
    }

    let user = await models.User.findOne({where: {username: username}})
    if (user) {
        return error(res, '用户名已经存在，请直接登录！')
    }

    // 生成盐
    const salt = bcrypt.genSaltSync(10)

    // 对用户填写的密码进行加密
    const hash = bcrypt.hashSync(password.toString(), salt)

    // 用户数据
    const body = {
        username: username,
        password: hash,
        admin: 1,
        roleId: roleId,
        avatar: avatar
    }

    // 插入数据库中
    user = await models.User.create(body)
    return success(res, '添加成功！', {user})
})

// 查询单条
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const user = await models.User.findByPk(id)
    if (!user) {
        return error(res, '当前用户不存在')
    }

    return success(res, '查询成功！', {user})
})

// 查询前端用户的订单
router.get('/:id/show_orders', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const user = await models.User.findByPk(id)
    if (!user) {
        return error(res, '当前用户不存在')
    }

    // 根据用户的 id 查出当前用户的订单
    const orders = await models.Order.findAll(
        {
            where: {userId: id},
            include: [
                {
                    model: models.OrderProduct,
                    as: 'products'
                },
                {
                    model: models.OrderAddress,
                    as: 'address'
                }
            ]
        }
    )

    return success(res, '查询成功！', {orders})
})

// 修改管理员
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const username = req.body.username
    const password = req.body.password
    const roleId = req.body.roleId
    const admin = toBoolean(req.body.admin)
    const avatar = req.body.avatar

    if (!username) {
        return error(res, '账号必须填写！')
    }

    if (!password) {
        return error(res, '密码必须填写！')
    }

    const user = await models.User.findByPk(id)
    if (!user) {
        return error(res, '当前用户不存在，无法修改')
    }

    // 生成盐
    const salt = bcrypt.genSaltSync(10)

    // 对用户填写的密码进行加密
    const hash = bcrypt.hashSync(password.toString(), salt)

    // 用户数据
    const body = {
        username: username,
        password: hash,
        roleId: roleId,
        admin: admin,
        avatar: avatar
    }

    user.update(body)
    return success(res, '修改成功！', {user})
})

// 删除管理员
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const user = await models.User.findByPk(id)
    if (!user) {
        return error(res, '当前用户不存在，无法删除')
    }

    user.destroy()
    return success(res, '删除成功！')
})

// 修改管理员状态
router.patch('/:id/toggle_admin', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const user = await models.User.findByPk(id)
    if (!user) {
        return error(res, '当前用户不存在，无法修改')
    }

    user.update({admin: !user.admin})
    success(res, '修改成功', {user})
})

module.exports = router
